import 'package:color_dart/color_dart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:im_flutter_sdk_example/components/a_button/index.dart';
import 'package:im_flutter_sdk_example/provider/group_formdate_model.dart';
import 'package:im_flutter_sdk_example/provider/group_message.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:im_flutter_sdk_example/utils/user_utils.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:im_flutter_sdk_example/utils/user.dart';
import 'package:im_flutter_sdk_example/utils/screen.dart';

class PasswordLogin extends StatefulWidget {
  PasswordLogin({Key key}) : super(key: key);

  _LoginMailState createState() => _LoginMailState();
}

class _LoginMailState extends State<PasswordLogin> {
  static Map phoneNumber = {"value": "15635370988", "verify": true};
  static Map passwd = {"value": "zc123321", "verify": true};

  // static Map phoneNumber = {"value": "", "verify": true};
  // static Map passwd = {"value": "", "verify": true};

  SharedPreferences prefs;

  @override
  void initState() {
    super.initState();
    EasyLoading.dismiss();
  }

  /// 登录
  login() async {
    if (!phoneNumber['verify'] || phoneNumber['value'] == null) {
      return G.toast('输入手机号有误');
    }
    if (!passwd['verify'] || passwd['value'] == null) {
      return G.toast('输入密码有误（最少8位）');
    }
    print('手机号${phoneNumber['value']}密码${passwd['value']}');

    /// 登录前移除user， 不然登录会提示token错误
    // prefs.remove('user');
    try {
      G.showLoading();
      var res = await G.req.user.passwordLogin(
          phoneNumber: phoneNumber['value'], passwd: passwd['value']);
      EasyLoading.dismiss();
      print("after login res: ${res.data['status']}");
      if (res.data['status'] != 1) {
        return;
      }
      //获取小组通知
      GroupMessageProvider groupProvider =
          Provider.of<GroupMessageProvider>(context);
      groupProvider.loadMessage();
      //获取我的小组信息
      GroupFormDataModel _formData = Provider.of<GroupFormDataModel>(context);
      _formData.getMyGroup();
      G.user.init(res.data['data']);
      // 环信 登录
      bool hasLoginout = await EMClient.getInstance.logout();
      if (hasLoginout) {
        User user = G.user;
        print("after login user: ${user.data.accountHead}");
        String imId =
            await EMClient.getInstance.login("${user.data.userId}", "123456");
        // await EMClient.getInstance.login("34", "123456");
        if (imId != null) {
          // G.toast('登录成功');
          // 判断 是否设置了 感兴趣标签
          bool hasTag = await UserUtils.hasTag();
          if (hasTag) {
            G.relaunch("routeName");
          } else {
            G.pushNamed('/select_interest');
          }
        }
      }
    } catch (e) {
      G.toast('登录失败');
    }
  }

  getUserDetail(String token) async {
    var res = await G.req.user.detail();

    var data = res.data;

    Map json = data['data']['base'];
    json['token'] = token;

    G.user.init(json);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: customAppbar(context: context, borderBottom: false, actions: [
        GestureDetector(
          onTap: () {
            G.pushNamed("/login_registe");
          },
          child: Padding(
            padding: EdgeInsets.only(right: 20, top: 10.h),
            child: Text("注册",
                style: TextStyle(color: rgba(51, 51, 51, 1), fontSize: 34.nsp)),
          ),
        )
      ]),
      body: Container(
        color: hex('#fff'),
        padding: EdgeInsets.only(left: 15, right: 15, top: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('密码登录',
                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold)),
            Container(
              height: 55,
              margin: EdgeInsets.only(top: 20),
              decoration: BoxDecoration(border: G.borderBottom()),
              child: TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                    counterText: "",
                    border: InputBorder.none,
                    hintText: '输入手机号',
                    hintStyle: TextStyle(
                      color: rgba(163, 163, 163, 1),
                      fontSize: 16,
                    )),
                onChanged: (e) {
                  RegExp regExp = RegExp(
                      r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
                  setState(() {
                    phoneNumber['value'] = e;

                    phoneNumber['verify'] = regExp.hasMatch(e);
                  });
                },
              ),
            ),
            Container(
              height: 55,
              margin: EdgeInsets.only(top: 10),
              decoration: BoxDecoration(border: G.borderBottom()),
              child: TextField(
                keyboardType: TextInputType.text,
                obscureText: true,
                decoration: InputDecoration(
                    counterText: "",
                    border: InputBorder.none,
                    hintText: '输入密码',
                    hintStyle: TextStyle(
                      color: rgba(163, 163, 163, 1),
                      fontSize: 16,
                    )),
                onChanged: (e) {
                  if (e.length >= 8) {
                    setState(() {
                      passwd['verify'] = true;
                    });
                  } else {
                    setState(() {
                      passwd['verify'] = false;
                    });
                  }
                  setState(() {
                    passwd['value'] = e;
                  });
                },
              ),
            ),

            /// 协议
            Container(
              width: double.infinity,
              margin: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '点击确定，即表示以阅读并同意',
                    style:
                        TextStyle(fontSize: 12, color: rgba(153, 153, 153, 1)),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () => {
                        Navigator.pushNamed(context, '/user_agreement'),
                      },
                      child: Container(
                          child: Text.rich(TextSpan(children: [
                        TextSpan(
                            text: '《隐私政策》',
                            style: TextStyle(
                                fontSize: 12, color: rgba(25, 109, 236, 1))),
                        TextSpan(
                            text: '及',
                            style: TextStyle(
                                fontSize: 12, color: rgba(51, 51, 51, 1))),
                        TextSpan(
                            text: '《服务协议》',
                            style: TextStyle(
                                fontSize: 12, color: rgba(25, 109, 236, 1)))
                      ]))),
                    ),
                  )
                ],
              ),
            ),

            /// 登录
            Container(
              margin: EdgeInsets.only(top: 25),
              child: AButton.normal(
                  width: double.infinity,
                  child: Text('登录'),
                  color: hex('#fff'),
                  bgColor: rgba(42, 125, 250, 1),
                  borderColor: rgba(136, 175, 213, 1),
                  onPressed: () => login()),
            ),

            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  AButton.normal(
                      child: Text('验证码快捷登录'),
                      color: rgba(51, 51, 51, 1),
                      onPressed: () => G.pushNamed('/login_phone')),
                  AButton.normal(
                      child: Text('忘记密码'),
                      color: rgba(51, 51, 51, 1),
                      onPressed: () => login())
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
